package com.example.springbootlogin.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.springbootlogin.annotation.AuthAccess;
import com.example.springbootlogin.domain.User;
import com.example.springbootlogin.exception.ServiceException;
import com.example.springbootlogin.repository.UserDao;
import com.example.springbootlogin.utils.TokenUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserDao userDao;

    @Resource
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取方法上的注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查是否有@AuthAccess注解，有则跳过认证
        if (method.isAnnotationPresent(AuthAccess.class)) {
            return true;
        }

        // 从请求头获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            throw new ServiceException("401", "请登录");
        }

        // 获取token中的用户ID
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new ServiceException("401", "token无效");
        }

        // 查询数据库验证用户是否存在
        User user = userDao.findById(Long.valueOf(userId)).orElse(null);
        if (user == null) {
            throw new ServiceException("401", "用户不存在");
        }

        // 验证token是否有效
        if (!tokenUtils.verify(token, user)) {
            throw new ServiceException("401", "token已过期或无效");
        }

        return true;
    }
}